package org.yray.sip.handler;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import org.yray.sip.base.AuthUtils;
import org.yray.sip.base.Authorization;
import org.yray.sip.base.MsgEle;
import org.yray.sip.base.SipMsg;
import org.yray.sip.creator.MessageCreator;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;


public class UnauthorizedHandler  extends MessageHandler  {

    @Override
    public String[] handler(SipMsg sipMsg, SipServerContext ssc) {
        SipSession sipSession=new SipSession(sipMsg,ssc.getRunIp(),ssc.getRunPort(),false);
        String ext=sipSession.getFrom();
        sipSession.setExt(ext);
        Authorization authorization=new Authorization(sipMsg.getMsgLine(MsgEle.WWW_AUTHENTICATE),MsgEle.AUTHORIZATION);
        authorization.getEleMap().put(Authorization.USERNAME,ext);
        authorization.getEleMap().put(Authorization.URI,"sip:"+ssc.getSipIp()+":"+ssc.getSipPort());
        authorization.getEleMap().put(Authorization.RESPONSE,Authorization.RESPONSE);
        authorization.getEleMap().put(Authorization.CNONCE, SecureUtil.md5(RandomUtil.randomNumber()+""));
        authorization.getEleMap().put(Authorization.NC,"00000001");
        authorization= AuthUtils.encryption(authorization, ssc.getSipExtTable().getExtPassword(ext));
        sipSession.setAuthorization(authorization.toString());
        String result= MessageCreator.getCreator(sipMsg.getMsgType()).createMsg(sipSession);
        return new String[]{result};
    }
}
